package com.example.JcGQS.service.impl;




import com.alibaba.fastjson.JSONArray;
import com.example.JcGQS.ElasticsearchApiExample.ElasticsearchApiExample;
import com.example.JcGQS.dao.GoodsDao;
import com.example.JcGQS.dao.HrmsDao;
import com.example.JcGQS.exception.CustomException;
import com.example.JcGQS.pojo.dto.*;
import com.example.JcGQS.pojo.entity.Goods;
import com.example.JcGQS.pojo.vo.*;
import com.example.JcGQS.service.GoodsService;
import com.example.JcGQS.util.JwtUtil;
import com.example.JcGQS.util.OrderUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName GoodsServiceImpl
 * @Description 物料表 服务实现类
 *
 * @author 末日
 * @date 2023/11/21
 */
@Service
@Slf4j
public class GoodsServiceImpl  implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private HrmsDao hrmsDao;
@Autowired
private ElasticsearchApiExample elasticsearchApiExample;

    /**
     * 新增物料
     */
    @Override
    public void insertGoods(InsertGoodsDTO insertGoodsDTO, String token) {
        Integer userId = JwtUtil.getUserIdByJWT(token);
        Integer integer = hrmsDao.permissionSelect(userId, "procurement_administrator");
        if (integer == 0){
            //无权限
            throw new CustomException("暂无该权限!!");
        }
        //型号一样不能添加
        Integer integer1 = goodsDao.goodsSelectName(insertGoodsDTO.getCategoryId(),insertGoodsDTO.getGoodsName(), insertGoodsDTO.getGoodsSpecification(), insertGoodsDTO.getGoodsModel(), insertGoodsDTO.getGoodsUnit(),insertGoodsDTO.getBrand());
        if (!"/".equals(insertGoodsDTO.getGoodsModel())){
            Integer integer3 = goodsDao.goodsSelectGoodsModel(insertGoodsDTO.getGoodsModel());
            if (integer3 != 0){
                throw new CustomException("该型号物料数据已存在");
            }
        }
        if (integer1==0){
            Goods goods = new Goods();
           BeanUtils.copyProperties(insertGoodsDTO,goods);
            String number = "WL"+ OrderUtil.createOrderNumber();
           goods.setGoodsNumber(number);
//            System.out.println(goods);
            goodsDao.insertGoods(goods);

            GoodsListVo goods1 = goodsDao.goodsSelectNumber(number);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("goods_id",goods1.getGoodsId());
            jsonObject.put("goods_number", goods1.getGoodsNumber());
            jsonObject.put("category_id",goods1.getCategoryId());
            jsonObject.put("category_name",goods1.getCategoryName());
            jsonObject.put("good_name", goods1.getGoodsName());
            jsonObject.put("goods_specification", goods1.getGoodsSpecification());
            jsonObject.put("goods_model", goods1.getGoodsModel());
            jsonObject.put("goods_unit",goods1.getGoodsUnit());
            jsonObject.put("brand",goods1.getBrand());
            jsonObject.put("goods_create_time",goods1.getGoodsCreateTime());
            jsonObject.put("goods_update_time",goods1.getGoodsUpdateTime());
            try {
                elasticsearchApiExample.insertData(goods1.getGoodsId(),jsonObject);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            throw new CustomException("该物料已存在");
        }

    }

    /**
     * 删除物料
     */
    @Override
    public void deleteGoods(DeleteGoodsDTO deleteGoodsDTO, String token) {
        Integer userId = JwtUtil.getUserIdByJWT(token);
        Integer integer = hrmsDao.permissionSelect(userId, "procurement_administrator");
        if (integer == 0){
            //无权限
            throw new CustomException("暂无该权限!!");
        }
        Integer integer1 = goodsDao.goodsSelect(deleteGoodsDTO.getGoodsId());
        if (integer1!=0){
            GoodsListVo goods1 = goodsDao.goodVoSelectId(deleteGoodsDTO.getGoodsId());
            try {
                elasticsearchApiExample.deleteData(goods1.getGoodsId());
                log.info("删除的物料数据为:{}",goods1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            goodsDao.deleteGoods(deleteGoodsDTO);
        }else {
            throw new CustomException("该物料不存在");
        }
    }
    /**
     * 更新物料
     *
     */
    @Override
    public void updateGoods(UpdateGoodsDTO updateGoodsDTO, String token) {
        long startTime = System.currentTimeMillis();


        Integer userId = JwtUtil.getUserIdByJWT(token);
        Integer integer = hrmsDao.permissionSelect(userId, "procurement_administrator");
        if (integer == 0){
            //无权限
            throw new CustomException("暂无该权限!!");
        }
        Integer integer2 = goodsDao.goodsSelect(updateGoodsDTO.getGoodsId());
        if (integer2!=0){
            Integer integer1 = goodsDao.goodsSelectName(updateGoodsDTO.getCategoryId(),updateGoodsDTO.getGoodsName(), updateGoodsDTO.getGoodsSpecification(), updateGoodsDTO.getGoodsModel(), updateGoodsDTO.getGoodsUnit(),updateGoodsDTO.getBrand());
            if (!"/".equals(updateGoodsDTO.getGoodsModel())){


            Integer integer3 = goodsDao.goodsSelectGoodsModel( updateGoodsDTO.getGoodsModel());
if (integer3 != 0){
    throw new CustomException("该型号物料数据已存在");
}
            }
            if (integer1==0){
                Goods  goods = new Goods();
                BeanUtils.copyProperties(updateGoodsDTO,goods);
                goodsDao.updateGoods(goods);

                GoodsListVo goods1 = goodsDao.goodVoSelectId(goods.getGoodsId());

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("goods_id",goods1.getGoodsId());
                jsonObject.put("goods_number", goods1.getGoodsNumber());
                jsonObject.put("category_id",goods1.getCategoryId());
                jsonObject.put("category_name",goods1.getCategoryName());
                jsonObject.put("good_name", goods1.getGoodsName());
                jsonObject.put("goods_specification", goods1.getGoodsSpecification());
                jsonObject.put("goods_model", goods1.getGoodsModel());
                jsonObject.put("goods_unit",goods1.getGoodsUnit());
                jsonObject.put("brand",goods1.getBrand());
                jsonObject.put("goods_create_time",goods1.getGoodsCreateTime());
                jsonObject.put("goods_update_time",goods1.getGoodsUpdateTime());
                try {
                    elasticsearchApiExample.insertData(goods1.getGoodsId(),jsonObject);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                throw new CustomException("该物料数据已存在");
            }

        }else {
            throw new CustomException("该物料不存在");
        }
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        System.out.println("程序执行时间：" + duration + " 毫秒");
    }

    /**
     * 搜索物料
     * @return
     */
    @Override
    public DataRecordsVO<GoodsListVo> searchGoods(SearchGoodsDTO searchGoodsDTO, String token) {
        Integer userId = JwtUtil.getUserIdByJWT(token);
//        Integer integer = hrmsDao.permissionSelect(userId, "purchase_authority");
//        if (integer == 0){
//            //无权限
//            throw new CustomException("暂无该权限!!");
//        }
        try {
            String builder = elasticsearchApiExample.globalSearch(searchGoodsDTO.getValue());

            JSONObject jsonObject = JSON.parseObject(builder);
            JSONObject hits = jsonObject.getJSONObject("hits");
            List<GoodsListVo> goodsList = new ArrayList<>();
            JSONArray hitsArray = hits.getJSONArray("hits");
            System.out.println("********");
            System.out.println(hitsArray);
            System.out.println("********");
            for (int i = 0; i < hitsArray.size(); i++) {
                JSONObject firstHit = hitsArray.getJSONObject(i);
                JSONObject source = firstHit.getJSONObject("_source");
                GoodsListVo goods = new GoodsListVo(

                        source.getInteger("goods_id"),
                        source.getString("goods_number"),
                        source.getInteger("category_id"),
                        source.getString("category_name"),
                        source.getString("good_name"),
                        source.getString("goods_specification"),
                        source.getString("goods_model"),
                        source.getString("goods_unit"),
                        source.getString("brand")
                );

                String goods_create_time = source.getString("goods_create_time");
                DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                LocalDateTime createTime = LocalDateTime.parse(goods_create_time, formatter);
                String goods_update_time = source.getString("goods_update_time");
                LocalDateTime updateTime = LocalDateTime.parse(goods_update_time, formatter);
               goods.setGoodsCreateTime(createTime);
               goods.setGoodsUpdateTime(updateTime);

//                System.out.println(goods);
                goodsList.add(goods);
            }

            // 起始索引
            int startIndex = (searchGoodsDTO.getPageDTO().getPage() - 1) * searchGoodsDTO.getPageDTO().getNum();
            // 结束索引
            int endIndex = Math.min(startIndex + searchGoodsDTO.getPageDTO().getNum(), goodsList.size());
            // 截取分页结果
            List<GoodsListVo> list = goodsList.subList(startIndex, endIndex);
         //   List<GoodsListVo> list = goodsList.subList(0, Math.min(goodsList.size(), 20));
            return new DataRecordsVO<>(goodsList.size(),list);
//            {
//                "took":6,
//                    "timed_out":false,
//                    "_shards":{
//                "total":1,
//                        "successful":1,
//                        "skipped":0,
//                        "failed":0
//            },
//                "hits":{
//                "total":{
//                    "value":1,
//                            "relation":"eq"
//                },
//                "max_score":1.0,
//                        "hits":[{
//                    "_index":"example_index",
//                            "_type":"_doc",
//                            "_id":"1",
//                            "_score":1.0,
//                            "_source":{
//                        "field1":"覅哦红旗分光"
//                    }
//                }]
//            }
//            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     *  查询物料列表
     */
    @Override
    public DataRecordVo<GoodsListVo> goodsList(PageDTO pageDTO, String token) {
       // Integer userId = JwtUtil.getUserIdByJWT(token);

        PageHelper.startPage(pageDTO.getPage(), pageDTO.getNum());
        log.info("11");
        List<GoodsListVo> goodsCategories = goodsDao.goodsList();

//        System.out.println(goodsCategories);
        PageInfo<GoodsListVo> pageInfo = new PageInfo<>(goodsCategories);
        return new DataRecordVo<>(pageInfo.getTotal(),pageInfo.getList());

    }





    /**
     * @Title listCategory
     * @Description 所有物品分类
     *
     * @return List<GoodsVo>
     */

    @Override
    public List<GoodsVo> listCategory() {
        return listGoodsAttribute("1", new GoodsAttributeVo());
    }

    /**
     * @Title listGoodsName
     * @Description 物品名称
     *
     * @param goodsAttributeVo
     * @return List<GoodsVo>
     */
    @Override
    public List<GoodsVo> listGoodsName(GoodsAttributeVo goodsAttributeVo) {
        return listGoodsAttribute("2", goodsAttributeVo);
    }

    /**
     * @Title listSpecification
     * @Description 物品规格
     *
     * @param goodsAttributeVo
     * @return List<GoodsVo>
     */
    @Override
    public List<GoodsVo> listSpecification(GoodsAttributeVo goodsAttributeVo) {
        return listGoodsAttribute("3", goodsAttributeVo);
    }

    /**
     * @Title listModel
     * @Description 物品型号
     *
     * @param goodsAttributeVo
     * @return List<GoodsVo>
     */
    @Override
    public List<GoodsVo> listModel(GoodsAttributeVo goodsAttributeVo) {
        return listGoodsAttribute("4", goodsAttributeVo);
    }



    /**
     * @Title listUnit
     * @Description 物品单位
     *
     * @return List<GoodsVo>
     */
    @Override
    public List<GoodsVo> listUnit() {
        return listGoodsAttribute("6", new GoodsAttributeVo());
    }

    /**
     * @Title listGoodsAttribute
     * @Description 查询物品属性
     * 
     * @param columCode
     *            查询字段代号
     * @param goodsAttributeVo
     *            查询条件
     * @return List<GoodsVo>
     */
    private List<GoodsVo> listGoodsAttribute(String columCode, GoodsAttributeVo goodsAttributeVo) {
        return goodsDao.listGoodsAttribute(columCode, goodsAttributeVo);
    }

}
